package com.itpan.Controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itpan.Entity.Customer;
import com.itpan.Entity.Product;
import com.itpan.Entity.StatsByPrice;
import com.itpan.Entity.StatsByT;
import com.itpan.Service.CustomerService;
import com.itpan.Service.ProductService;
import com.itpan.Utils.CustomerExcelListener;
import com.itpan.Utils.EntityValidate;
import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


/*
auth：itpan
潘志鹏，2024/6/18开始写供应商接口


2024/6/19 修改:      加上优化和缓存处理
 */

@Api(value = "供应商相关接口")
@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private ProductService productService;

    @Autowired
    private EntityValidate entityValidate;

    /*
    查询所有
     */
    @Cacheable(value = "customer",key = "'all'")   //缓存处理
    @GetMapping("/getall")
    @ApiOperation(value = "查询所有供应商")
    public R<List<Customer>> getall(){
        List<Customer> list = customerService.getall();
        return R.success(list);
    }


    /*
    查询所有带分页
     */
    @GetMapping("/getpage")
    @ApiOperation(value = "查询供应商带分页")
    @Cacheable(value = "customer",key = "#p0"+'-'+"#p1")
    public R<List<Customer>> getallPage(Integer page,Integer pageSize){
        List<Customer> list = customerService.getallPage(page, pageSize);
        return R.success(list);
    }


    /*
    模糊查询带表格
     */
    @ApiOperation(value = "查询供应商模糊带表格")
    @PostMapping("/getmutiltable")
    public void getallpage(@RequestBody Customer customer,HttpServletResponse response) throws IOException {
        List<Customer> list = customerService.getbymutil(customer);
        setExcelRespProp(response, "供应商列表");

        EasyExcel.write(response.getOutputStream(), Customer.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("供应商列表")
                .doWrite(list);
        response.getOutputStream().flush();  // Ensure all data is written to the response
    }


    @ApiOperation("查询全部带表格")
    @GetMapping("/getalltable")
    public void getalltable(HttpServletResponse response) throws IOException {
        List<Customer> list=customerService.getall();
        setExcelRespProp(response, "供应商列表");

        EasyExcel.write(response.getOutputStream(), Customer.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("供应商列表")
                .doWrite(list);
        response.getOutputStream().flush();  // Ensure all data is written to the response
    }



    /*
    迷糊查询
     */
    @PostMapping("/mutil")
    @ApiOperation(value = "模糊查询不带表格接口")
    public R<List<Customer>> getbymutil(@RequestBody Customer customer){
        List<Customer> list = customerService.getbymutil(customer);
        return R.success(list);
    }



    /**
     * 根据id查询供应商

     */



    /*
    新增一个供应商
     */
    @CacheEvict(value = "customer",allEntries = true)
    @PostMapping("/addone")
    @ApiOperation("新增一个供应商")
    public R<String> addone(@RequestBody Customer customer){
        if(!entityValidate.isValidateOfCustomer(customer)){
            return R.error("供应商信息填写错误");
        }
        customerService.addone(customer);
        return R.success("新增成功");
    }


    /*
    批量新增供应商数据
     */
    @CacheEvict(value = "customer",allEntries = true)
    @PostMapping("/addall")
    @ApiOperation(value = "导入表格批量导入供应商")
    public R<String> addall(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return R.error("文件不能为空");
        }
        EasyExcel.read(file.getInputStream(),Customer.class,new CustomerExcelListener(customerService, entityValidate))
        .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doRead();;
        return R.success("添加成功");
    }






    /**
     * 根据id删除接口
     * @param
     * @return
     */
    @CacheEvict(value = "customer",allEntries = true)
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除供应商接口")
    public R<String> deletebyId(String id){

        List<Product> list=productService.getbycid(id);
        if (list.size()>0){
            return R.error("删除失败，还有具体商品练习此供应商");
        }

        customerService.deleteById(id);
        return R.success("删除成功");
    }


    @CacheEvict(value = "customer",allEntries = true)
    @ApiOperation(value = "更新供应商")
    @PostMapping("/update")
    public R<String> update(@RequestBody Customer customer){
        if(!entityValidate.isValidateOfCustomer(customer)){
            return R.error("供应商信息填写错误");
        }
        customerService.update(customer);
        return R.success("更新成功");



    }


    @ApiOperation(value = "统计供应商地域分布")
    @GetMapping("/countByProvince")
    public R<List<StatsByT>> countSuppliersByProvince() {
        List<StatsByT> counts = customerService.countSuppliersByProvince();
        return R.success(counts);
    }

    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // Ensure the file is not cached
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }



}
